package com.jhz.speedy.common.util;

import java.text.DecimalFormat;

/**
 * 数字工具
 * Created by JunHeZ on 2017/7/14.
 */
public class NumUtils {

    /**
     * 字节数组其中一段，转成数字
     * @param index 起始位置
     * @param length  长度
     */
    public static long bytesToLong(byte[] data, int index, int length) {
        long num = 0;
        for (int i = 0; i < length; i++) {
            num = num << 8 | (long)data[index + i];
        }
        return num;
    }

    /**
     * 字节数组其中一段，转成数字
     * @param index 起始位置
     */
    public static long bytesToLong(byte[] data, int index) {
        long num = (0x000000ff & (int) data[index]) * 256 * 256 * 256 + (0x000000ff & (int) data[index + 1]) * 256 * 256 + (0x000000ff & (int) data[index + 2]) * 256 + (0x000000ff & (int) data[index + 3]);
        return num;
    }

    /**
     * 获取百分比
     * @param imax 最大数
     * @return 99%
     */
    public static Double getRate(long mun, long imax) {
        double doble = 0;
        double max = 0;
        max = intToDouble(imax);
        if (max <= 0)
            return 0.00;

        double size = 0;
        size = intToDouble(mun);

        if (size <= 0)
            return 0.00;
        doble = size / max * 100;

        return doble;
    }

    /**
     * int 转 Double
     * @param num 数
     * @return
     */
    public static Double intToDouble(long num) {
        Double dou = 0.00;
        try {
            dou = new Long(num).doubleValue();
        } catch (Exception e) {
            dou = 0.00;
        }
        return dou;
    }

    /**
     * 数字转 字符串，保留一位数字
     * @param double1
     * @return
     */
    public static String FormetDoubleString(Double double1) {
        DecimalFormat df = new DecimalFormat("0.0");
        String str = df.format((double) double1);
        return str;
    }
}
